import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    //属性的webView
    let webView = UIWebView()
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    //MARK:本地代码和webView交互
    @objc private func testAccount() {
        let jsString = "document.getElementById('userId').value = '18334728736' , document.getElementById('passwd').value = 'woaiziji1234'"
        //通过一个字符串对象来执行 javascipt代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        SVProgressHUD.dismiss()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .Plain, target: self, action: "testAccount")
        
        loadOauthPage()
    }
    //MARK:使用webView加载授权界面
    func loadOauthPage() {
        //client_id
        //redirect_uri
        //App Key：2541468108
        //App Secret：4856163a6e9e45876e059908ee6fbd6a
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        //获取request对象
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
    }
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}
//extension必须等到本类结束后 才可以进行扩展
extension OAuthViewController:UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        //开启指示器
        SVProgressHUD.show()
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        //关闭指示器
        SVProgressHUD.dismiss()
    }
    //获取收取成功后的code(授权码)
    //shouldStartLoadWithRequest 每次加载新的页面 都会重新发起一个request
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        guard let urlString = request.URL?.absoluteString else {
            //urlString 为空
            return false
        }
        //判断urlString中是否包含code码
        if urlString.containsString("code") {
            //query 获取url的参数的字段和对应值
            guard let query = request.URL?.query else {
                return false
            }
            let codeStr = "code="
            // 雷区 NSString.substringToIndex
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            //            print(code)
            //用code码换取令牌
            //            loadAccessToken(code)
            UserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
                if isSuccess {
                    //如果登录成功就
                    self.dismissViewControllerAnimated(true, completion: nil)
                    NSNotificationCenter.defaultCenter().postNotificationName(KChoseRootVC, object: nil)
                }else{
                    SVProgressHUD.showErrorWithStatus("网络连接失败,请检查您的网络")
                }
            })
            return false
        }
        return true
    }
}
